package com.study.happystudy.tool;

import com.google.gson.Gson;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * 七牛云存储工具类
 *
 */
@Component
public class KoDoTool {
    @Value("${project.qiniuyunkey}") //用途：是从application.yml中获取对应的key值
    private String key;//七牛云的key
    @Value("${project.qiniuyunsecret}") //用途：是从application.yml中获取对应的key值
    private String secret;//七牛云的密码
    @Value("${project.qiniuyunbucket}") //用途：是从application.yml中获取对应的key值
    private String bucket;//七牛云的桶名称
    @Value("${project.qiniuyunbucketurl}") //用途：是从application.yml中获取对应的key值
    private String bucketUrl;//七牛云的桶URL
    private static final Logger logger= LoggerFactory.getLogger(KoDoTool.class);//日志getLogger需要传入的类名

    /**
     * 上传文件到七牛云存储
     * @param filePath 本地文件路径
     * @return String 文件在线访问地址
     */
    public String UploadFile(String filePath){
        String fileName= UUID.randomUUID()+"."+filePath.split("\\.")[1];//重新生成文件名
        try{//生成七牛云的配置对象，Configuration需要传入bucket的地域，地域选择错误就会上传失败
            Configuration configuration=new Configuration(Region.huadong());
            UploadManager uploadManager=new UploadManager(configuration);//配置上传对象
            Auth auth= Auth.create(key,secret);//根据七牛云key和secret生成上传token
            String token=auth.uploadToken(bucket);
            Response response= uploadManager.put(filePath,fileName,token);//上传文件并返回结果
            DefaultPutRet putRet= new Gson().fromJson(response.bodyString(),DefaultPutRet.class);//将返回结果解析
            logger.info(putRet.toString());//输出结果
        }catch (Exception e){
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        return bucketUrl+"/"+fileName;
    }
//    public String UploadFile(MultipartFile file){
//        String fileName= UUID.randomUUID()+"."+file.getName().split("\\.")[1];//重新生成文件名
//        try{//生成七牛云的配置对象，Configuration需要传入bucket的地域，地域选择错误就会上传失败
//            Configuration configuration=new Configuration(Region.huadong());
//            UploadManager uploadManager=new UploadManager(configuration);//配置上传对象
//            Auth auth= Auth.create(key,secret);//根据七牛云key和secret生成上传token
//        } catch (Exception e){
//            logger.error(e.getMessage());
//            e.printStackTrace();
//        }
//        return bucketUrl+"/"+fileName;
//    }


    /**
     * 上传文件到七牛云存储
     * @param file MultipartFile
     * @return String 文件在线访问地址
     * @throws Exception
     */
    public String upload(MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new RuntimeException("文件是空的");
        }
        // 创建上传token
        Auth auth = Auth.create(key, secret);
        String upToken = auth.uploadToken(bucket);
        // 设置上传配置，Region要与存储空间所属的存储区域保持一致
        Configuration cfg = new Configuration(Region.region0());

        // 创建上传管理器
        UploadManager uploadManager = new UploadManager(cfg);

        String originalFilename = file.getOriginalFilename();
        // 构造文件目录和文件名
        assert originalFilename != null;
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileKey = UUID.randomUUID() + suffix;
        // 上传文件
        Response response = uploadManager.put(file.getInputStream(), fileKey, upToken, null, null);
        // 返回文件url
        return bucketUrl + fileKey;
    }
}
